package com.yami.shop.api.controller;



import com.yami.shop.bean.model.Invoice;
import com.yami.shop.bean.model.Order;

import com.yami.shop.common.response.ServerResponseEntity;

import com.yami.shop.service.InvoiceService;
import com.yami.shop.service.OrderService;
import com.yami.shop.service.UserService;
import jakarta.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;

import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 发票申请表 前端控制器
 * </p>
 *
 * @author jcd
 * @since 2024-08-19
 */
@RestController
@RequestMapping("/p/invoice")
public class InvoiceController {
    @Autowired
    private UserService userService;
    @Autowired
    private InvoiceService invoiceService;

    @Autowired
    private OrderService orderService;


    /**
     * 通过id查询开票申请
     *
     * @param id id
     * @return 单个数据
     */
    @GetMapping("/info/{id}")
    public ServerResponseEntity<Invoice> getById(@PathVariable("id") Long id) {
        return ServerResponseEntity.success(invoiceService.getById(id));
    }

    /**
     * 新增申请
     * @return 是否新增成功
     */
    @PostMapping("/apply")
    public ServerResponseEntity<Boolean> apply(@RequestBody @Valid Invoice invoice) {
        Invoice one = invoiceService.lambdaQuery().eq(Invoice::getOrderId, invoice.getOrderId()).one();
        if(one != null){
            return ServerResponseEntity.showFailMsg("订单的发票申请已存在");
        }
        invoice.setCreateTime(new Date());
        //invoice.setCreateBy(userId);
        invoice.setDelFlag(0);
        invoice.setState(0);//申请中

        Order byId = orderService.getById(invoice.getOrderId());
        if (byId != null){
            invoice.setOrderNumber(byId.getOrderNumber());
            invoice.setProdName(byId.getProdName());
            invoice.setProductNums(byId.getProductNums());
            invoice.setUid(byId.getUserId());
        }

        return ServerResponseEntity.success(invoiceService.save(invoice));
    }

    /**
     * 重新设置申请原因,再次提交开票申请
     * @param invoice
     * @return
     */
    @PostMapping("/reApply")
    public ServerResponseEntity<Boolean> reApply(@RequestBody @Valid Invoice invoice) {
        Invoice byId = invoiceService.getById(invoice.getId());
        List<Integer> integers = Arrays.asList(0, 2);
        if(!integers.contains(byId.getState())){
            return ServerResponseEntity.showFailMsg("当前状态不能再次提交申请");
        }

        Invoice invoice1=new Invoice();
        invoice1.setId(byId.getId());
        invoice1.setApplyReason(invoice.getApplyReason());
        invoice1.setApplyTitle(invoice.getApplyTitle());
        invoice1.setState(0);//申请中

        return ServerResponseEntity.success(invoiceService.updateById(invoice1));
    }
}

